package com.example.thread_local_demo.interceptor;

import com.example.thread_local_demo.constant.MyConstant;
import com.example.thread_local_demo.entity.UserInfoTo;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.LinkedHashMap;
import java.util.UUID;

/**
 * @author xh
 * @Date 2022/10/21
 */
public class MyInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        // 获取用户登录信息
        HttpSession session = request.getSession();
        LinkedHashMap loginUser = (LinkedHashMap) session.getAttribute("loginUser");

        UserInfoTo userInfoTo = new UserInfoTo();
        if (loginUser != null) {
            userInfoTo.setUserId(Long.parseLong(loginUser.get("id").toString()));
        }

        // 遍历cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (int i = 0; i < cookies.length; i++) {
                // 判断是否是游客
                if (MyConstant.TEMP_USER_COOKIE_NAME.equals(cookies[i].getName())) {
                    userInfoTo.setUserKey(cookies[i].getValue());
                }
            }
        }

        threadLocal.set(userInfoTo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        UserInfoTo userInfoTo = threadLocal.get();

        if (userInfoTo.getUserKey() == null || "".equals(userInfoTo.getUserKey())) {
            userInfoTo.setUserKey(UUID.randomUUID().toString());
        }

        Cookie cookie = new Cookie(MyConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
        cookie.setMaxAge(MyConstant.TEMP_USER_COOKIE_EXPIRE_TIME);

        response.addCookie(cookie);
    }

}
